package com.demo.example;

import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 大量List数据批量插入数据库很高效的方法
 * https://lixinkuan.blog.csdn.net/article/details/109656677
 * @author gy
 * @date 2022/7/21
 */
public class SubListBigData {
    public static void main(String[] args) {
//        /**
//         * 定义 用户商品数据 分批插入的上限值
//         */
//        private static final int USER_NUM = 90;
//
//        @Override
//        @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
//        @Async("AsyncPoolTaskExecutor")
//        public CompletableFuture<ResponseModel> generateDefaultUserGoodsDetail(Integer receiveRuleGroupId,
//                Integer operatorId, Integer orgId) {
//            String baseLog = "领取规则组id["+ receiveRuleGroupId + "],运营商id[" + operatorId + "],机构id[" + orgId + "]";
//            logger.info("为"+baseLog+"生成*默认用户*商品领用数据开始");
//            // 1、通过 默认规则组id 查询到所有用户 共同的 用户商品信息
//            List<ReceiveDefaultUserGoodsDetail> defaultUserGoodsDetails = getMapper().
//                    selectDefaultDetailByGroupId(receiveRuleGroupId);
//            if (defaultUserGoodsDetails.isEmpty()){
//                logger.error("未能查询到有用户 共同的 用户商品信息" + baseLog);
//                throw new CommonException(MsgProperties.getFailResp("未能查询到有用户 共同的 用户商品信息",baseLog));
//            }
//            // 2、获取到 该运营商、机构下的 所有用户
//            List<Integer> userList = mgEnterpriseWechatUserMapper.selectAllUserId(operatorId, orgId);
//            if (userList.isEmpty()){
//                logger.error("未能获取到 该运营商、机构下的 用户信息" + baseLog);
//                throw new CommonException(MsgProperties.getFailResp("未能获取到 该运营商、机构下的 用户信息",baseLog));
//            }
//
//            long startTime = System.currentTimeMillis();
//
//            // 3、将所有的用户进行分段
//            int listSize = userList.size();
//            int toIndex = USER_NUM;
//            for (int i = 0; i < userList.size(); i += USER_NUM) {
//
//                if (i + USER_NUM > listSize) {
//                    // 作用为toIndex最后没有 90 条数据则剩余几条newList中就装几条
//                    toIndex = listSize - i;
//                }
//                List<Integer> subNewList = userList.subList(i, i + toIndex);
//
//                // 用来存储需要批量 插入的 数据
//                List<ReceiveDefaultUserGoodsDetail> batchGoodsDetailList = new ArrayList<>();
//
//                // a.将分段后的list 的每个 item 都封装为一个 newDefaultUserGoodsDetailList ,每个 item 中有 9条数据
//                subNewList.stream().forEach(userId -> {
//                    List<ReceiveDefaultUserGoodsDetail> newDefaultUserGoodsDetailList = defaultUserGoodsDetails.stream()
//                            .map((ReceiveDefaultUserGoodsDetail gd) -> {
//                                ReceiveDefaultUserGoodsDetail duModel = new ReceiveDefaultUserGoodsDetail();
//                                duModel.setReceiveRuleGroupId(gd.getReceiveRuleGroupId());
//                                duModel.setReceiveUserId(gd.getReceiveUserId());
//                                duModel.setReceiveRuleId(gd.getReceiveRuleId());
//                                duModel.setReceiveGoodsId(gd.getReceiveGoodsId());
//                                duModel.setGoodsLimitNum(gd.getGoodsLimitNum());
//                                duModel.setGoodsSource(gd.getGoodsSource());
//                                duModel.setGoodsResetTime(gd.getGoodsResetTime());
//                                duModel.setRemainNum(gd.getRemainNum());
//                                duModel.setOperatorId(gd.getOperatorId());
//                                duModel.setOrgId(gd.getOrgId());
//                                duModel.setStatus(gd.getStatus());
//                                duModel.setCreateTime(gd.getCreateTime());
//                                duModel.setUpdateTime(gd.getUpdateTime());
//                                return duModel;
//                            }).collect(Collectors.toList());
//                    // 给每个对象的 ReceiveUserId 赋值
//                    for (ReceiveDefaultUserGoodsDetail receiveDefaultUserGoodsDetail : newDefaultUserGoodsDetailList) {
//                        receiveDefaultUserGoodsDetail.setReceiveUserId(userId);
//                    }
//                    batchGoodsDetailList.addAll(newDefaultUserGoodsDetailList);
//                });
//                // b.开始执行批量插入
//                int insertBatchNum = getMapper().insertBatch(batchGoodsDetailList);
//                if (!(insertBatchNum > 0)) {
//                    throw new CommonException(MsgProperties.getFailResp("后台批量插入默认规则组 用户商品明细失败",batchGoodsDetailList));
//                }
//            }
//
//            long endTime = System.currentTimeMillis();
//            logger.info("为"+baseLog+"生成*默认用户*商品领用数据结束");
//            logger.info("为"+baseLog+"批量插入默认规则组 用户商品明细成功,耗时：" + (endTime-startTime) + " ms");
//            return CompletableFuture.completedFuture(MsgProperties.
//                    getSuccess("批量插入默认规则组 用户商品明细成功,耗时：" + (endTime - startTime) + " ms"));
//        }
    }
}
